<template>
    <div class="wrap">
        <!-- 栅格。gutter表示缝隙。 -->
        <el-row class="row" :gutter="20">
            <el-col :span="6">
                <div class="grid">
                    <span>学院：</span>

                    <el-select v-model="nowChoose.collegeId" placeholder="请选择学院" :clearable="true">
                        <el-option v-for="(item, index) in allCollege" :key="index" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </div>
            </el-col>

            <el-col :span="6">
                <div class="grid">
                    <span>专业：</span>
                    <el-select v-model="nowChoose.majorId" placeholder="请选择专业" :clearable="true">
                        <el-option v-for="(item, index) in allMajarsInNowCollege" :key="index" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </div>
            </el-col>

            <el-col :span="6">
                <div class="grid">
                    <span>班级：</span>
                    <el-select v-model="nowChoose.classId" placeholder="请选择班级" :clearable="true">
                        <el-option v-for="(item, index) in allClassInNowMajor" :key="index" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </div>
            </el-col>

            <el-col :span="6">
                <div class="grid">
                    <span>入学年份：</span>
                    <el-select v-model="nowChoose.ey" placeholder="请选择入学年份" :clearable="true">
                        <el-option v-for="(item, index) in [2019, 2020, 2021, 2022]" :key="index" :label="item"
                            :value="item"></el-option>
                    </el-select>
                </div>
            </el-col>
        </el-row>

        <el-row class="row" :gutter="20">
            <el-col :span="6">
                <div class="grid">
                    <span>性别：</span>
                    <el-select v-model="nowChoose.sex" placeholder="请筛选性别" :clearable="true">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                    </el-select>
                </div>
            </el-col>

            <el-col :span="6">
                <div class="grid">
                    <span>政治面貌：</span>
                    <el-select v-model="nowChoose.ps" placeholder="请筛选政治面貌" :clearable="true">
                        <el-option label="党员" value="党员"></el-option>
                        <el-option label="预备党员" value="预备党员"></el-option>
                        <el-option label="共青团员" value="共青团员"></el-option>
                    </el-select>
                </div>
            </el-col>

            <el-col :span="6">
                <div class="grid">
                    <span>民族：</span>
                    <el-select v-model="nowChoose.minzu" placeholder="请筛选民族" :clearable="true">
                        <el-option label="汉族" value="1"></el-option>
                        <el-option label="少数民族" value="2"></el-option>
                    </el-select>
                </div>
            </el-col>

            <el-col :span="6">
                <div class="grid">
                    <span>在读状态：</span>
                    <el-select v-model="nowChoose.state" placeholder="请筛选在读状态" :clearable="true">
                        <el-option label="在读" value="1" />
                        <el-option label="休学" value="2" />
                        <el-option label="退学" value="3" />
                    </el-select>
                </div>
            </el-col>
        </el-row>


        <el-row class="row" :gutter="20">
            <el-col :span="8">
                <div class="grid">
                    <span>生日范围：</span>
                    <!-- 日期范围框 -->
                    <el-date-picker type="daterange" v-model="nowChoose.birthDayRange" value-format="timestamp"
                        :default-value="new Date(2000, 0, 1)"></el-date-picker>
                </div>
            </el-col>
            <el-col :span="8">
                <div class="grid">
                    <span>关键字：</span>
                    <!-- 输入框 -->
                    <el-input placeholder="可以查询姓名、手机号、学号" v-model="nowChoose.kw" clearable></el-input>
                </div>
            </el-col>
            <el-col :span="4">
                <div class="grid">
                    <!-- 按钮，type="success" 表示绿色按钮 -->
                    <el-button type="success" @click="searchClick">搜索</el-button>
                </div>
            </el-col>
        </el-row>


        <el-row class="row">
            <el-col :span="24">
                当前正在筛选：
                <el-tag closable v-show="filter.collegeId" @close="clearAndReload('collegeId')">学院id：{{ filter.collegeId
                }}</el-tag>

                <el-tag closable v-show="filter.majorId" @close="clearAndReload('majorId')">专业id：{{ filter.majorId }}
                </el-tag>

                <el-tag closable v-show="filter.classId" @close="clearAndReload('classId')">班级id：{{ filter.classId }}
                </el-tag>

                <el-tag closable v-show="filter.ey" @close="clearAndReload('ey')">
                    入学年份：{{ filter.ey }}
                </el-tag>

                <el-tag closable v-show="filter.sex" @close="clearAndReload('sex')">性别：{{ filter.sex }}</el-tag>

                <el-tag closable v-show="filter.ps" @close="clearAndReload('ps')">政治面貌：{{ filter.ps }}</el-tag>

                <el-tag closable v-show="filter.minzu" @close="clearAndReload('minzu')">民族：{{
                        showMinzu(filter.minzu)
                }}</el-tag>

                <el-tag closable v-show="filter.state" @close="clearAndReload('state')">在读状态：{{
                        showState(filter.state)
                }}
                </el-tag>

                <el-tag closable v-if="filter.birthDayRange && filter.birthDayRange.length != 0"
                    @close="clearAndReload('birthDayRange')">
                    生日范围：{{ filter.birthDayRange.map(item => moment(item).format('YYYY年MM月DD日')).join(' 到 ') }}
                </el-tag>

                <el-tag closable v-show="filter.kw" @close="clearAndReload('kw')">
                    关键字：{{
                            filter.kw
                    }}
                </el-tag>
            </el-col>
        </el-row>

        <!-- 分页条 -->
        <el-pagination background :total="total" :current-page="currentPage" :page-size="pageSize"
            @current-change="changePage($event)" @size-change="changePagesize($event)"
            layout="prev, pager, next, sizes, total" :page-sizes="[5, 10, 20, 30]"></el-pagination>

        <!-- 表格 -->
        <el-table :data="tableData" style="width: 100%">
            <el-table-column label="头像" width="120">
                <template slot-scope="scope">
                    <img :src="`http://www.zkt-it.com:5050/images/student_avatar/${scope.row.avatar}`" class="avatar">
                </template>
            </el-table-column>

            <el-table-column label="学号" prop="sId"></el-table-column>

            <el-table-column label="姓名" prop="name"></el-table-column>

            <el-table-column label="手机号" prop="tel"></el-table-column>

            <el-table-column label="入学年份" prop="enrollmentYear"></el-table-column>

            <el-table-column label="生日">
                <template slot-scope="scope">
                    {{ moment(scope.row.birthDay).format('YYYY-MM-DD') }}
                </template>
            </el-table-column>

            <el-table-column label="学院名称" prop="collegeName"></el-table-column>

            <el-table-column label="专业名称" prop="majorName"></el-table-column>

            <el-table-column label="班级名称" prop="className"></el-table-column>

            <el-table-column label="性别" prop="sex"></el-table-column>

            <el-table-column label="政治面貌" prop="politics_status"></el-table-column>

            <el-table-column label="民族" prop="nationality"></el-table-column>


            <el-table-column label="学生状态">
                <template slot-scope="scope">
                    <!-- 1在读、2休学、3退学 -->
                    <el-tag type="success" v-show="scope.row.state == 1" :disable-transitions="true">
                        在读
                    </el-tag>

                    <el-tag type="warning" v-show="scope.row.state == 2" :disable-transitions="true">
                        休学
                    </el-tag>

                    <el-tag type="danger" v-show="scope.row.state == 3" :disable-transitions="true">
                        退学
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200"  fixed="right">
                <template slot-scope="scope">
                    <div>
                        <!-- 气泡确认框，包裹按钮 -->
                        <el-popconfirm :title="'真的要删除' + scope.row.name + '么？'" @confirm="delStudent(scope.row.sId)">
                            <!-- 按钮是气泡确认框的插槽了 -->
                            <el-button slot="reference" size="mini" type="danger">
                                删除
                            </el-button>
                        </el-popconfirm>
                    </div>

                    <div style="margin-top: 4px;">
                        <el-button size="mini" type="warning" @click="$router.push({
                            name: '修改学生',
                            query: {
                                sid: scope.row.sId
                            }
                        })">
                            修改
                        </el-button>
                    </div>

                    <div style="margin-top: 4px;">
                        <el-button size="mini" type="success" @click="$router.push({
                            name: '查看学生详情',
                            params: {
                                sid: scope.row.sId
                            }
                        })">
                            查看详情
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页条 -->
        <el-pagination background :total="total" :current-page="currentPage" :page-size="pageSize"
            @current-change="changePage($event)" @size-change="changePagesize($event)"
            layout="prev, pager, next, sizes, total" :page-sizes="[5, 10, 20, 30]"></el-pagination>
    </div>
</template>

<script>
import moment from 'moment';

// 引入Ajax函数
import { fetchStudent, fetchCMC, deleteStudent } from '@/api/student.js';
import MyCalendar from '@/components/LunarCalendar.vue';

export default {
    // 当前App.vue组件创建完毕，就会执行
    created() {
        // 调用methods中定义的loadData函数，也要加this.前缀
        this.loadData();
        // 拉取CMC数据（学院、专业、班级）
        this.loadCMC();
    },
    // 所有数据
    data() {
        return {
            // 当前正在修改的学生的学号
            nowModifySid: "",
            // 表格数组一定是空。
            tableData: [],
            // 总条数
            total: 0,
            // 当前页码
            currentPage: 1,
            // 每页几条
            pageSize: 10,
            // 用于下拉菜单等双向绑定显示的值
            nowChoose: {
                // 性别
                sex: "",
                // 政治面貌
                ps: "",
                // 民族
                minzu: "",
                // 状态
                state: "",
                // 学院id
                collegeId: "",
                // 专业id
                majorId: "",
                // 班级id
                classId: "",
                // 生日范围
                birthDayRange: [],
                // 关键字
                kw: "",
                // 入学年份
                ey: ""
            },
            // 过滤器
            filter: {},
            // 全部学院、专业、班级数据
            allcmc: []
        };
    },
    // 定义函数的地方
    methods: {
        // 写一写moment这个词语，表示moment:moment。目的是为了让{{}}中能够使用moment。
        moment,
        // 改变页码做的事情
        changePage(page) {
            // 先改Vue的data值
            this.currentPage = page;
            // 然后再拉取数据
            this.loadData();
        },
        // 改变每页多少条做的事情
        changePagesize(pagesize) {
            // 页码归1。就是说用户更改每页几条，我们就让页码归1即可。
            this.currentPage = 1;
            // 更改每页几条
            this.pageSize = pagesize;
            // 拉取数据
            this.loadData();
        },
        // 点击绿色搜索按钮
        searchClick() {
            // 页码归1
            this.currentPage = 1;
            // 覆盖。不能写this.filter = this.nowChoose。因为这样引用类型值传值了，内存中就是同一个对象了。引用类型赋值赋值的是内存地址，一个改变，另一个也会改变。
            // 千万不要this.filter = this.nowChoose
            this.filter = { ...this.nowChoose };
            // 拉
            this.loadData();
        },
        // 点击tab的×号，此时会清空一个属性，然后重新jiazai
        clearAndReload(k) {
            if (k == "birthDayRange") {
                this.filter[k] = [];
                this.nowChoose[k] = [];
            }
            else {
                // 让filter值，和展示值都清空
                this.filter[k] = "";
                this.nowChoose[k] = "";
            }
            // 加载数据
            this.loadData();
        },
        // 将民族数字变为字符串
        showMinzu(num) {
            if (num == 1) {
                return "汉族";
            }
            else if (num == 2) {
                return "少数民族";
            }
        },
        // 将在读状态数字变为字符串
        showState(num) {
            if (num == 1) {
                return "在读";
            }
            else if (num == 2) {
                return "休学";
            }
            else if (num == 3) {
                return "退学";
            }
        },
        // 请求学生数据
        async loadData() {
            // 罗列GET请求参数对象
            let params = {
                page: this.currentPage,
                pagesize: this.pageSize
            };
            // 如果filter中有sex，那么就让GET请求参数加上sex
            if (this.filter.sex) {
                params.sex = this.filter.sex;
            }
            // 如果filter中有ps，那么就让GET请求参数加上ps
            if (this.filter.ps) {
                params.ps = this.filter.ps;
            }
            // 如果filter中有minzu，那么就让GET请求参数加上na
            if (this.filter.minzu) {
                params.na = this.filter.minzu;
            }
            if (this.filter.state) {
                params.state = this.filter.state;
            }
            if (this.filter.collegeId) {
                params.coid = this.filter.collegeId;
            }
            if (this.filter.majorId) {
                params.maid = this.filter.majorId;
            }
            if (this.filter.classId) {
                params.clid = this.filter.classId;
            }
            if (this.filter.birthDayRange && this.filter.birthDayRange.length != 0) {
                params.bd = this.filter.birthDayRange.join("to");
            }
            if (this.filter.kw) {
                params.kw = this.filter.kw;
            }
            if (this.filter.ey) {
                params.ey = this.filter.ey;
            }
            // Ajax请求
            const res = await fetchStudent(params);
            // 把服务器数组替换表格数组
            this.tableData = res.results;
            // 把服务器总条数替换total值
            this.total = res.total;
        },
        // 请求cmc数据，c学院，m专业，c班级
        async loadCMC() {
            // 请求
            const res = await fetchCMC();
            // 写数据
            this.allcmc = res;
        },
        // 删除学生
        delStudent(sId) {
            // 删除用什么请求？DELETE
            deleteStudent(sId).then(() => {
                // 提示框，this.$message.success()是ElementUI的用法，表示弹出成功提示
                this.$message.success("删除学生成功");
                // 拉取数据
                this.loadData();
            }, (res) => {
                // 失败
                // 提示框，this.$message.error()是ElementUI的用法，表示弹出错误提示
                this.$message.error(res.response.data.info);
            });
        }
    },
    // 计算后属性，
    computed: {
        // 全部学院
        allCollege() {
            // 返回所有学院数组
            return this.allcmc.map(item => ({
                label: item.collegeName,
                value: item.collegeId
            }));
        },
        // 当前学院的全部专业
        allMajarsInNowCollege() {
            // Ajax是必须有时间才能返回的。
            // this.allcmc很可能是[]。Ajax返回之后，才是有值的
            // 尝试过滤
            // filter返回一个数组，所以要加[0]
            const result = this.allcmc.filter(item => item.collegeId == this.nowChoose.collegeId)[0];
            if (result != undefined) {
                return result.majors.map(item => ({
                    label: item.majorName,
                    value: item.majorId,
                }));
            }
        },
        // 当前学院、当前专业的全部班级
        allClassInNowMajor() {
            const result = this.allcmc.filter(item => item.collegeId == this.nowChoose.collegeId)[0];
            // 当result不是空，且专业id不是空的时候
            if (this.nowChoose.majorId != "") {
                return result.majors.filter(item => item.majorId == this.nowChoose.majorId)[0].classes.map(item => ({
                    label: item.className,
                    value: item.classId,
                }));
            }
        }
    },
    // 监控
    watch: {
        // 当学院id变化的时候，那么让专业id清空
        "nowChoose.collegeId"() {
            this.nowChoose.majorId = "";
        },
        // 当专业id变化的时候，那么让班级id清空
        "nowChoose.majorId"() {
            this.nowChoose.classId = "";
        }
    },
    components: { MyCalendar }
}
</script>

<style>
/* 头像的样式 */
.avatar {
    width: 100px;
    height: 100px;
}

.row {
    margin-bottom: 20px;
}

.tool_box_1 {
    display: flex;
}

.tool_box_1 .btn {
    margin-left: 10px;
}

.el-tag {
    margin-right: 10px;
}

.grid {
    display: flex;
    align-items: center;
}

.grid .el-select {
    flex: 1;
}

.grid .el-input {
    flex: 1;
}
</style>
